package com.elong.businesstravel.base.recorder.listener;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import com.android.support.jhf.dialog.CustomDialogView;
import com.android.support.jhf.utils.ToolUtils;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.recorder.Recorder;
import com.elong.businesstravel.base.recorder.VUMeter;

import android.app.Service;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.Vibrator;
import android.text.format.Time;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class RecordOnTouchListener implements OnLongClickListener,
		OnTouchListener {

	private CustomDialogView mCustomDialogView;
	private Context mContext;
	private TextView mTipTextView;
	private View mRecordView;

	private int lastX, lastY;
	private long mStart = 0;
	private long mEnd = 0;

	private Recorder mRecorder;

	private IRecordingListener mIRecordingListener;
	private IRecordingStateListener mIRecordingStateListener;

	private boolean isSend = true;
	// 倒计时
	private TextView mTimeView;

	private ImageView mTipImageView;

	private VUMeter mVUMeter;
	// 是否在录音
	private boolean isRecording = true;
	// 录音时间
	private int mRecordTime = 0;

	boolean longClicked = false;

	boolean isFirst = false;

	public RecordOnTouchListener(Context context,
			CustomDialogView customDialogView, View view, View recordView,
			Recorder recorder, IRecordingListener iRecordingListener,
			IRecordingStateListener iRecordingStateListener) {
		mCustomDialogView = customDialogView;
		mContext = context;
		mRecordView = recordView;
		mRecorder = recorder;
		mIRecordingStateListener = iRecordingStateListener;
		mIRecordingListener = iRecordingListener;

		mRecordView.setOnLongClickListener(this);

		if (null != view) {
			mTimeView = (TextView) view.findViewById(R.id.timeTextView);
			mTipTextView = (TextView) view.findViewById(R.id.tipsTextView);
			if (null == mCustomDialogView) {
				mTipTextView.setVisibility(View.INVISIBLE);
			}
			mTipImageView = (ImageView) view.findViewById(R.id.tipImageView);
			mVUMeter = (VUMeter) view.findViewById(R.id.uvMeter);
		}

	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN: {
			// Log.e("onTouch", "down");
			lastX = (int) event.getRawX();
			lastY = (int) event.getRawY();

			// mRecordButton.setBackgroundResource(R.drawable.btn_stop_record);
			break;
		}
		case MotionEvent.ACTION_MOVE: {

			// Log.e("onTouch", "move");

			int move = lastY - (int) event.getRawY();
			// Print.println("move : " + move);
			if (move > 0
					&& Math.abs(move) > ToolUtils.getTouchSlop(mContext)
							+ ToolUtils.dipToPx(mContext, 20)) {

				isSend = false;
				cancelSendRecording();

			} else {

				if (longClicked && isFirst) {

					startRecording();
					isFirst = false;

				}

			}
			break;
		}
		case MotionEvent.ACTION_UP: {

			// Log.e("onTouch", "up");

			if (longClicked) {

				mEnd = System.currentTimeMillis();
				long duration = mEnd - mStart;

				if (duration <= mRecorder.getRecordMinLenght()*1000) {// 小于一秒钟不发送

					isSend = false;
					timeShort();

				} else {
					sendRecording();
				}
			}

			longClicked = false;

			// mRecordButton.setBackgroundResource(R.drawable.btn_pressed_start_record);
			break;
		}
		default:
			break;
		}
		return false;
	}

	/**
	 * 开始录音
	 */
	private void startRecording() {

		isRecording = true;

		if (null != mIRecordingStateListener) {
			mIRecordingStateListener.startRecordingUI();
		} else {
			if (null != mCustomDialogView)
				mCustomDialogView.showDialog();
			mTipImageView.setVisibility(View.INVISIBLE);
			mVUMeter.setVisibility(View.VISIBLE);
		}

		mIRecordingListener.startRecording();

		new Thread() {
			public void run() {

				while (isRecording) {

					if (null != mIRecordingStateListener) {
						mIRecordingStateListener.progressUI(mRecordTime);
					}

					if (mRecordTime > (mRecorder.getRecordMaxLenght()-10) && mRecordTime <= mRecorder.getRecordMaxLenght()) {

						if (null != mIRecordingStateListener) {
							mIRecordingStateListener.with10SecondsLeftUI(mRecorder.getRecordMaxLenght() - mRecordTime);
						} else {
							mHandler.sendEmptyMessage(1);
						}

					}

					if (mRecordTime == mRecorder.getRecordMaxLenght()) {
						isRecording = false;
						mHandler.sendEmptyMessage(2);
					}

					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					mRecordTime++;
				}

			}
		}.start();

	}

	/**
	 * 停止录音
	 */
	private void stopRecording() {

		isRecording = false;
		mRecordTime = 0;

		if (null != mIRecordingStateListener) {
			mIRecordingStateListener.stopRecordingUI();
		} else {
			if (null == mCustomDialogView) {
				mTipTextView.setVisibility(View.INVISIBLE);
			}
			mTipTextView.setText("手指上滑，取消发送");
			mTimeView.setVisibility(View.INVISIBLE);
			mTipImageView.setVisibility(View.INVISIBLE);
			mVUMeter.setVisibility(View.VISIBLE);
			if (null != mCustomDialogView)
				mCustomDialogView.hideDialog();
		}

		mRecorder.stop();

		if (isSend)
			mIRecordingListener.stopRecording();

		isSend = true;

	}

	/**
	 * 发送语音
	 */
	private void sendRecording() {
		stopRecording();
	}

	/**
	 * 取消发送语音删除文件
	 */
	private void cancelSendRecording() {

		deleteRecordFile();

		if (null != mIRecordingStateListener) {
			mIRecordingStateListener.slideToCancelSendingUI();
		} else {
			mTipTextView.setText("松开手指，取消发送");
			mTipImageView.setVisibility(View.VISIBLE);
			mTipImageView.setImageResource(R.drawable.icon_voice_cancel);
			mVUMeter.setVisibility(View.INVISIBLE);
			mTimeView.setVisibility(View.INVISIBLE);
		}

	}

	private void deleteRecordFile() {
		mRecorder.delete();
	}

	/**
	 * 时间太短，取消发送
	 */
	private void timeShort() {
		deleteRecordFile();

		if (null != mIRecordingStateListener) {
			mIRecordingStateListener.timeShortUI();
		} else {
			mTipTextView.setVisibility(View.VISIBLE);
			mTipTextView.setText("时间太短！");
			mTipImageView.setVisibility(View.VISIBLE);
			mTipImageView.setImageResource(R.drawable.icon_voice_prompt);
			mVUMeter.setVisibility(View.INVISIBLE);
			mTimeView.setVisibility(View.INVISIBLE);
		}

		Timer timer = new Timer();
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				mHandler.sendEmptyMessage(0);
			}
		}, 500);

	}

	Handler mHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case 0:

				stopRecording();

				break;

			case 1: {

				mTipImageView.setVisibility(View.INVISIBLE);
				mVUMeter.setVisibility(View.INVISIBLE);
				mTimeView.setVisibility(View.VISIBLE);

				mTipTextView.setText("每次限时" + mRecorder.getRecordMaxLenght() + "秒");
				mTimeView.setText((mRecorder.getRecordMaxLenght() - mRecordTime) + "");

				break;
			}

			case 2: {

				if (null != mTipTextView) {
					mTipTextView.setText("录音完毕，松开发送");
				}

				mRecorder.stop();

				break;
			}
			default:
				break;
			}
			return false;
		}
	});

	@Override
	public boolean onLongClick(View v) {

		// Log.e("onLongClick", "long");

		Vibrator mVibrator = (Vibrator) mContext
				.getSystemService(Service.VIBRATOR_SERVICE);
		mVibrator.vibrate(100);

		mStart = System.currentTimeMillis();
		longClicked = true;
		isFirst = true;

		MotionEvent e = MotionEvent.obtain(SystemClock.uptimeMillis(),
				SystemClock.uptimeMillis(), MotionEvent.ACTION_MOVE, lastX + 1,
				lastY, 0);

		mRecordView.dispatchTouchEvent(e);

		return false;
	}

}